"""
Tree-sitter主分析器
提供命令行接口和完整的项目分析功能
"""

import argparse
import sys
import os
from pathlib import Path
from typing import Dict, List, Any, Optional
import json
import time

from project_analyzer import ProjectAnalyzer


class TreeSitterCLI:
    """Tree-sitter命令行界面"""
    
    def __init__(self):
        self.analyzer: Optional[ProjectAnalyzer] = None
    
    def run(self):
        """运行命令行程序"""
        parser = self._create_argument_parser()
        args = parser.parse_args()
        
        if args.command == "analyze":
            self._analyze_project(args)
        elif args.command == "query":
            self._query_symbols(args)
        else:
            parser.print_help()
    
    def _create_argument_parser(self) -> argparse.ArgumentParser:
        """创建命令行参数解析器"""
        parser = argparse.ArgumentParser(
            description="Tree-sitter 项目级语法树分析工具"
        )
        
        subparsers = parser.add_subparsers(dest="command", help="可用命令")
        
        # analyze 命令
        analyze_parser = subparsers.add_parser("analyze", help="分析项目")
        analyze_parser.add_argument("--project-path", required=True, help="项目路径")
        analyze_parser.add_argument("--output", "-o", help="输出文件路径")
        
        # query 命令
        query_parser = subparsers.add_parser("query", help="查询符号")
        query_parser.add_argument("--project-path", required=True, help="项目路径")
        query_parser.add_argument("--name", help="符号名称")
        
        return parser
    
    def _analyze_project(self, args):
        """分析项目"""
        print(f"正在分析项目: {args.project_path}")
        
        self.analyzer = ProjectAnalyzer(project_path=args.project_path)
        
        try:
            summary = self.analyzer.analyze_project()
            print("分析完成!")
            
        except Exception as e:
            print(f"分析失败: {e}")
            sys.exit(1)
    
    def _query_symbols(self, args):
        """查询符号"""
        print(f"正在加载项目: {args.project_path}")


def main():
    """主函数"""
    try:
        cli = TreeSitterCLI()
        cli.run()
    except KeyboardInterrupt:
        print("程序被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"程序出错: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()